import Vue from 'vue'
import Vuex from 'Vuex'
import axios from 'axios'

Vue.use(Vuex);

export default new Vuex.Store({
    state:{
        products:[],
        buyList:[]
    },
    mutations:{
        changeProduct(state,products){
            state.products = products;
        },
        addProduct(state,obj){
            let bIndex = state.buyList.findIndex(item => item.id === obj.id);
            if(bIndex != -1){
                state.buyList[bIndex].num++;
            }else{
                obj.num = 1;
                obj.status = false;
                state.buyList.push(obj)
            }
            state.buyList = state.buyList.concat([]);
        },
        check(state,{id,status}){
            let bItem = state.buyList.find(item => item.id === id);
            bItem.status = !bItem.status;
            state.buyList = state.buyList.concat([]);
        },
        count(state,{num,id}){
            state.buyList.forEach(item => {
                if(item.id === id){
                    item.num = num;
                }
            })
            state.buyList = state.buyList.concat([]);
        },
        checkAllFun(state,status){
            state.buyList.forEach(item => {
                item.status = status
            })
            state.buyList = state.buyList.concat([]);
        }
    },
    getters:{
        totalCount(state){
            return state.buyList.reduce((pre,cur) => {
                return pre + cur.num
            },0)
        },
        totalMoney(state){
            return state.buyList.reduce((pre,cur) => {
                let money = cur.status ? cur.num * cur.price : 0;
                return pre + money
            },0)
        }
    },
    actions:{
        getData({commit}){
            axios.get('/api/product').then(res => {
                if(res.data.code === 1){
                    commit('changeProduct',res.data.data)
                }
            })
        }
    }
})

